﻿using System;
using Microsoft.SharePoint;
using NHibernate;
using OpenWaves.ActivityFeed.NHibernate;

namespace OpenWaves.ActivityFeed.Sharepoint
{
    public  abstract class ActivityFeedEventReceiverBase : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);
            this.ExecuteSessionScopeAction((connector)=> connector.OnItemEvent(properties, SPEventReceiverType.ItemAdded));
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            //base.ItemUpdated(properties);
            this.ExecuteSessionScopeAction((connector) => connector.OnItemEvent(properties, SPEventReceiverType.ItemUpdated));
        }

        protected void ExecuteSessionScopeAction(Action<IActivityFeedSharepointConnector> sessionAction)
        {
            var sessionFactory = new NHibernateSessionFactory(new NHibernateSessionFactoryConfiguration("dsad"));
            using (var session = sessionFactory.CreateSessionFactory().OpenSession())
            {
                session.FlushMode = FlushMode.Commit;
                using (var transaction = session.BeginTransaction())
                {
                    var connector = this.CreateConnector(new NHibernateActivityFeedService(session));
                    sessionAction(connector);
                    transaction.Commit();
                }
            }
        }

        protected abstract string ConnectionString { get; }

        protected virtual IActivityFeedSharepointConnector CreateConnector(IActivityFeedService activityFeedService)
        {
            return new ActivityFeedSharepointConnectorBase(activityFeedService);
        }
    }
}
